package com.berchen.utils;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 */
public class SpinLock {

    AtomicReference<Thread> atomicLock = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"加锁了");
        // 如果保存的是null  就设置为thread
        while (!atomicLock.compareAndSet(null,thread)){
//            System.out.println("自旋中");
        }
    }
    public void unlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"释放锁了");

        atomicLock.compareAndSet(thread,null);
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        for (int i = 0; i < 5; i++) {

            new Thread(()->{

                spinLock.lock();

                try {
                    System.out.println(Thread.currentThread().getName()+"正在执行 其他线程进不来");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                spinLock.unlock();
            }).start();

        }
    }
}
